from rest_framework import serializers
from .models import Order, OrderItem, OrderStatusHistory, RefundRequest, ShippingAddress


class ShippingAddressSerializer(serializers.ModelSerializer):
    class Meta:
        model = ShippingAddress
        fields = ['id', 'name', 'phone', 'province', 'city', 'district', 
                 'address', 'postal_code', 'is_default']
        read_only_fields = ['id']


class OrderItemSerializer(serializers.ModelSerializer):
    book_title = serializers.CharField(source='book.title', read_only=True)
    book_image = serializers.ImageField(source='book.cover_image', read_only=True)
    
    class Meta:
        model = OrderItem
        fields = ['id', 'book', 'book_title', 'book_image', 'quantity', 'price', 'subtotal']
        read_only_fields = ['id', 'subtotal']


class OrderListSerializer(serializers.ModelSerializer):
    items = OrderItemSerializer(many=True, read_only=True)
    shipping_address = ShippingAddressSerializer(read_only=True)
    
    class Meta:
        model = Order
        fields = [
            'id', 'order_number', 'total_amount', 'final_amount',
            'status', 'payment_status', 'shipping_address',
            'items', 'created_at', 'updated_at'
        ]


class OrderDetailSerializer(serializers.ModelSerializer):
    items = OrderItemSerializer(many=True, read_only=True)
    shipping_address = ShippingAddressSerializer(read_only=True)
    status_history = serializers.SerializerMethodField()
    
    class Meta:
        model = Order
        fields = [
            'id', 'order_number', 'user', 'total_amount', 'discount_amount',
            'shipping_fee', 'final_amount', 'status', 'payment_status',
            'shipping_address', 'tracking_number', 'shipping_method',
            'notes', 'items', 'status_history', 'created_at', 'updated_at',
            'paid_at', 'shipped_at', 'delivered_at'
        ]
    
    def get_status_history(self, obj):
        history = obj.status_history.all().order_by('-created_at')
        return OrderStatusHistorySerializer(history, many=True).data


class OrderCreateSerializer(serializers.ModelSerializer):
    items = OrderItemSerializer(many=True)
    shipping_address = ShippingAddressSerializer()
    
    class Meta:
        model = Order
        fields = ['items', 'shipping_address', 'notes']
    
    def create(self, validated_data):
        items_data = validated_data.pop('items')
        shipping_data = validated_data.pop('shipping_address')
        
        # 获取当前用户
        user = self.context['request'].user
        
        # 创建或获取收货地址
        shipping_address, created = ShippingAddress.objects.get_or_create(
            user=user,
            **shipping_data
        )
        
        # 创建订单
        order = Order.objects.create(
            user=user,
            shipping_address=shipping_address,
            **validated_data
        )
        
        # 创建订单项
        total_amount = 0
        for item_data in items_data:
            book = item_data['book']
            quantity = item_data['quantity']
            price = book.discount_price or book.price
            
            # 检查库存
            if book.stock_quantity < quantity:
                raise serializers.ValidationError(
                    f"商品 {book.title} 库存不足，当前库存: {book.stock_quantity}"
                )
            
            OrderItem.objects.create(
                order=order,
                book=book,
                quantity=quantity,
                price=price,
                subtotal=price * quantity
            )
            
            # 更新库存
            book.stock_quantity -= quantity
            book.save()
            
            total_amount += price * quantity
        
        # 更新订单总金额
        order.total_amount = total_amount
        order.final_amount = total_amount
        order.save()
        
        return order


class OrderStatusHistorySerializer(serializers.ModelSerializer):
    class Meta:
        model = OrderStatusHistory
        fields = ['status', 'note', 'created_at']


class RefundRequestSerializer(serializers.ModelSerializer):
    class Meta:
        model = RefundRequest
        fields = ['id', 'order', 'reason', 'description', 'refund_amount', 
                 'status', 'admin_note', 'created_at']
        read_only_fields = ['id', 'status', 'admin_note', 'created_at']
    
    def create(self, validated_data):
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)


class RefundRequestAdminSerializer(serializers.ModelSerializer):
    class Meta:
        model = RefundRequest
        fields = ['id', 'order', 'user', 'reason', 'description', 'refund_amount',
                 'status', 'admin_note', 'processed_by', 'processed_at', 'created_at']
        read_only_fields = ['id', 'order', 'user', 'reason', 'description', 
                          'created_at', 'processed_by', 'processed_at']
